package com.example.myapplication;

import static android.graphics.Color.*;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
//import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = "Main";
    private UDPClient udpClient;
    private EditText etHostIP;
    private TextView XiLi1, XiLi2, Zuansu1, Dianliu1, Zuansu2, Dianliu2, Zuansu3, Dianliu3, Zuansu4, Dianliu4, udpCount, infoText;
    private Timer timer;
    private TimerTask task;
    private boolean isStop = true;
    private SharedPreferences.Editor editor;
    private Button btnConn;
    private int sendCount = 0, receCount = 0;
    private LineChart lineChart;
    private XAxis xAxis;    // X轴
    private YAxis yAxis;    // Y轴
    private ArrayList<Entry> values1, values2;
    private LineDataSet lineDataSet1, lineDataSet2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 定义控件
        XiLi1 = findViewById(R.id.XiLi1);
        XiLi2 = findViewById(R.id.XiLi2);
        Zuansu1 = findViewById(R.id.Zuansu1);
        Dianliu1 = findViewById(R.id.Dianliu1);
        Zuansu2 = findViewById(R.id.Zuansu2);
        Dianliu2 = findViewById(R.id.Dianliu2);
        Zuansu3 = findViewById(R.id.Zuansu3);
        Dianliu3 = findViewById(R.id.Dianliu3);
        Zuansu4 = findViewById(R.id.Zuansu4);
        Dianliu4 = findViewById(R.id.Dianliu4);
        udpCount = findViewById(R.id.udpCount);
        infoText = findViewById(R.id.infoText);

        // 读取初始参数
        Context ctx = MainActivity.this;
        SharedPreferences sp = ctx.getSharedPreferences("config", MODE_PRIVATE);
        etHostIP = findViewById(R.id.etHostIP);
        editor = sp.edit();
        etHostIP.setText(sp.getString("HostIP", "127.0.0.1"));

        // 定义按钮单击事件
        // lambda 方式
        btnConn = findViewById(R.id.btnConn);
        btnConn.setOnClickListener((View v) -> {
            Log.i(TAG, "1.发送UDP数据。");
            if (isStop) {
                startTimer();
                sendCount = 6;
                receCount = 0;
            } else {
                stopTimer();
            }
            isStop = !isStop;
        });

        // 曲线图表设置
        lineChart = findViewById(R.id.lineChart);
        lineChart.getDescription().setEnabled(false);
        lineChart.getAxisRight().setEnabled(false);    // 不绘制右侧的轴线

        //lineChart.setOnChartValueSelectedListener(this);

        // 获取X轴
        xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.TOP_INSIDE);  // X轴在顶部
        xAxis.setGranularity(1);
        xAxis.setDrawLabels(false);  // 是否绘制标签,默认true
        xAxis.setDrawAxisLine(true);    // 是否绘制坐标轴,默认true
        xAxis.setDrawGridLines(false);   // 是否绘制网格线，默认true

        // 获取Y轴
        yAxis = lineChart.getAxisLeft();
        yAxis.setSpaceTop(10);   // 设置最大值到图标顶部的距离占所有数据范围的比例。默认10，y轴独有
        yAxis.setSpaceBottom(10);   // 同上，只不过是最小值距离底部比例。默认10，y轴独有
        yAxis.enableGridDashedLine(10f, 10f, 0f);// Y 轴的水平网格线
//        yAxis.setAxisMaximum(0f);// 设置 Y 轴的数值范围
//        yAxis.setAxisMinimum(-2500f);

        values1 = new ArrayList<>();
        values2 = new ArrayList<>();
    }

    private void startTimer() {
        if (timer == null) {
            timer = new Timer();
        }
        if (task == null) {
            // 定义定时器处理函数
            task = new TimerTask() {
                @Override
                public void run() {
                    sendCount += 6;
                    udpClient = new UDPClient(etHostIP.getText().toString(), handler);
                    udpClient.start();  // 发送UDP数据
                    udpCount.setText(String.format(Locale.CHINA, "发送：%d Bytes；接收：%d Bytes", sendCount, receCount));
                }
            };
        }
        if (timer != null) {
            timer.schedule(task, 0, 1000);  // 开启定时器
            editor.putString("HostIP", etHostIP.getText().toString());  // 保存连接主机IP
            editor.commit();
            btnConn.setText("断开");
            etHostIP.setEnabled(false);
        }
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }
        btnConn.setText("连接");
        etHostIP.setEnabled(true);
    }

    // 接收子线程发送的数据
    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                receCount += 96;
                double d1 = msg.getData().getDouble("2");
                double d2 = msg.getData().getDouble("8");
                XiLi1.setText(String.format("-%3.1f Pa", d1));
                XiLi2.setText(String.format("-%3.1f Pa", d2));

                int i = values1.size();
//                if (i >= 60 * 0.5) {  // 如果超过30分钟的数据，就删除前面的一个数据
//                    values1.remove(0);
//                    values2.remove(0);
//                    //lineDataSet1.removeEntryByXValue(0);
//                    //lineDataSet2.removeEntryByXValue(0);
//                    //lineChart.getData().removeEntry(0,0);
//                    //lineChart.getData().removeEntry(0,1);
//                }
                values1.add(new Entry(i , (float) -d1));
                values2.add(new Entry(i , (float) -d2));
                //Log.i("MAX:",String.format("%f,%f",lineChart.getYChartMax(),lineChart.getYChartMin()));
                lineDataSet1 = new LineDataSet(values1, "吸力1");
                lineDataSet1.setAxisDependency(YAxis.AxisDependency.LEFT);
                lineDataSet1.setColor(ColorTemplate.getHoloBlue());
                lineDataSet1.setCubicIntensity(0.5f); // 设置曲率,0.05f-1f 1为折线
                lineDataSet1.setDrawCircles(false);
                lineDataSet1.setDrawValues(false); // 包含的数据的值文本
                lineDataSet1.setFillAlpha(65);
                lineDataSet1.setFillColor(ColorTemplate.getHoloBlue());
                lineDataSet1.setHighLightColor(Color.rgb(244, 117, 117));
                lineDataSet1.setDrawCircleHole(false);

                lineDataSet2 = new LineDataSet(values2, "吸力2");
                lineDataSet2.setColor(GREEN);
                lineDataSet2.setCubicIntensity(0.15f); // 设置曲率,0.05f-1f 1为折线
                lineDataSet2.setDrawCircles(false);
                lineDataSet2.setDrawValues(false);

                LineData lineData = new LineData();
                lineData.addDataSet(lineDataSet1);
                lineData.addDataSet(lineDataSet2);
                lineChart.setData(lineData);

                lineChart.notifyDataSetChanged();
                lineChart.setVisibleXRangeMaximum(60*10);  // X轴显示长度
                lineChart.moveViewToX(lineDataSet1.getXMax()-5);  // 移动X轴显示内容
                lineChart.invalidate();  // 重绘图形

                int ii = (int) Math.floor(msg.getData().getDouble("0"));
                Zuansu1.setText(String.format("%d r/min", ii));
                ii = (int) Math.floor(msg.getData().getDouble("3"));
                Zuansu2.setText(String.format("%d r/min", ii));
                ii = (int) Math.floor(msg.getData().getDouble("6"));
                Zuansu3.setText(String.format("%d r/min", ii));
                ii = (int) Math.floor(msg.getData().getDouble("9"));
                Zuansu4.setText(String.format("%d r/min", ii));

                Dianliu1.setText(String.format("%3.1f A", msg.getData().getDouble("1")));
                Dianliu2.setText(String.format("%3.1f A", msg.getData().getDouble("4")));
                Dianliu3.setText(String.format("%3.1f A", msg.getData().getDouble("7")));
                Dianliu4.setText(String.format("%3.1f A", msg.getData().getDouble("10")));

                infoText.setText(msg.getData().toString());

            }
        }
    };


}